package com.jvmmonitor.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 配置加载工具类
 */
public class ConfigLoader {
    private static final Logger logger = LoggerFactory.getLogger(ConfigLoader.class);
    
    // 配置文件名称
    private static final String CONFIG_FILE = "config/monitor-config.properties";
    
    // 配置实例
    private static Properties properties;
    
    // 配置项默认值
    private static final long DEFAULT_MONITOR_INTERVAL = 10000; // 默认10秒
    private static final boolean DEFAULT_OBJECT_CREATE_LOG_ENABLED = false; // 默认关闭对象创建日志
    private static final int DEFAULT_OBJECT_CREATE_LOG_SAMPLING_RATE = 10; // 默认10%采样率
    private static final long DEFAULT_SMALL_OBJECT_THRESHOLD = 1024; // 默认1KB
    private static final long DEFAULT_MEDIUM_OBJECT_THRESHOLD = 1048576; // 默认1MB
    private static final boolean DEFAULT_MEMORY_GROWTH_ANALYSIS_ENABLED = true; // 默认开启内存增长分析
    private static final boolean DEFAULT_JVM_ADVICE_ENABLED = true; // 默认开启JVM建议
    private static final boolean DEFAULT_PRODUCTION_MODE = false; // 默认不启用生产环境模式
    
    static {
        loadConfig();
    }
    
    /**
     * 加载配置文件
     */
    private static void loadConfig() {
        properties = new Properties();
        
        try (InputStream input = ConfigLoader.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (input != null) {
                properties.load(input);
                logger.info("Loaded configuration from {}", CONFIG_FILE);
            } else {
                logger.warn("Configuration file {} not found, using default values", CONFIG_FILE);
            }
        } catch (IOException e) {
            logger.error("Failed to load configuration file: {}", e.getMessage());
        }
    }
    
    /**
     * 获取监控间隔（毫秒）
     */
    public static long getMonitorInterval() {
        return getLongProperty("monitor.interval", DEFAULT_MONITOR_INTERVAL);
    }
    
    /**
     * 获取对象创建日志开关
     */
    public static boolean isObjectCreateLogEnabled() {
        return getBooleanProperty("object.create.log.enabled", DEFAULT_OBJECT_CREATE_LOG_ENABLED);
    }
    
    /**
     * 获取对象日志采样率（0-100）
     */
    public static int getObjectCreateLogSamplingRate() {
        return getIntProperty("object.create.log.sampling.rate", DEFAULT_OBJECT_CREATE_LOG_SAMPLING_RATE);
    }
    
    /**
     * 获取小对象阈值（字节）
     */
    public static long getSmallObjectThreshold() {
        return getLongProperty("object.size.small.threshold", DEFAULT_SMALL_OBJECT_THRESHOLD);
    }
    
    /**
     * 获取中等对象阈值（字节）
     */
    public static long getMediumObjectThreshold() {
        return getLongProperty("object.size.medium.threshold", DEFAULT_MEDIUM_OBJECT_THRESHOLD);
    }
    
    /**
     * 获取内存增长分析开关
     */
    public static boolean isMemoryGrowthAnalysisEnabled() {
        return getBooleanProperty("memory.growth.analysis.enabled", DEFAULT_MEMORY_GROWTH_ANALYSIS_ENABLED);
    }
    
    /**
     * 获取JVM参数建议开关
     */
    public static boolean isJvmAdviceEnabled() {
        return getBooleanProperty("jvm.advice.enabled", DEFAULT_JVM_ADVICE_ENABLED);
    }
    
    /**
     * 获取需要监控的包名列表（逗号分隔）
     */
    public static String getMonitorPackages() {
        return getStringProperty("monitor.packages", "");
    }
    
    /**
     * 获取需要监控的类名列表（逗号分隔）
     */
    public static String getMonitorClasses() {
        return getStringProperty("monitor.classes", "");
    }
    
    /**
     * 获取生产环境模式开关
     */
    public static boolean isProductionMode() {
        return getBooleanProperty("production.mode", DEFAULT_PRODUCTION_MODE);
    }
    
    /**
     * 获取字符串属性
     */
    public static String getStringProperty(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
    
    /**
     * 获取整数属性
     */
    public static int getIntProperty(String key, int defaultValue) {
        String value = properties.getProperty(key);
        if (value != null) {
            try {
                return Integer.parseInt(value);
            } catch (NumberFormatException e) {
                logger.warn("Invalid integer value for property {}: {}, using default {}", key, value, defaultValue);
            }
        }
        return defaultValue;
    }
    
    /**
     * 获取长整数属性
     */
    public static long getLongProperty(String key, long defaultValue) {
        String value = properties.getProperty(key);
        if (value != null) {
            try {
                return Long.parseLong(value);
            } catch (NumberFormatException e) {
                logger.warn("Invalid long value for property {}: {}, using default {}", key, value, defaultValue);
            }
        }
        return defaultValue;
    }
    
    /**
     * 获取布尔属性
     */
    public static boolean getBooleanProperty(String key, boolean defaultValue) {
        String value = properties.getProperty(key);
        if (value != null) {
            return Boolean.parseBoolean(value);
        }
        return defaultValue;
    }
    
    /**
     * 重新加载配置
     */
    public static void reload() {
        loadConfig();
    }
}